import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def plot_model_performance():
    # Load the data from CSV file
    df = pd.read_csv('../logs/model_performance_log.csv')

    # Take only the first 10 models (excluding header)
    df = df.head(10)

    # Identify model types for color grouping
    df['Model Type'] = 'CNN-based'
    df.loc[df['Model'].str.contains('LSTM'), 'Model Type'] = 'LSTM-based'
    df.loc[df['Model'].str.contains('Transformer'), 'Model Type'] = 'Transformer-based'

    # Sort models by accuracy for better visualization
    df = df.sort_values('Test Accuracy (%)', ascending=False)

    # Set global styling
    sns.set_style("whitegrid")
    plt.rcParams.update({'font.size': 12})

    # Convert EER values to percentage for better visualization
    df['Global EER (%)'] = df['Global EER'] * 100
    df['Avg Per-User EER (%)'] = df['Avg Per-User EER'] * 100

    # Plot 1: Test Accuracy
    plt.figure(figsize=(12, 8))
    bars = sns.barplot(x='Model', y='Test Accuracy (%)', hue='Model Type', data=df, palette='viridis')
    plt.title('Test Accuracy by Model', fontsize=16)
    plt.xticks(rotation=45, ha='right')
    plt.ylim(98, 100)  # Focus on the important range
    for i, bar in enumerate(bars.patches):
        bars.annotate(f"{bar.get_height():.2f}%",
                     (bar.get_x() + bar.get_width()/2, bar.get_height()),
                     ha='center', va='bottom', fontsize=10)
    plt.tight_layout()
    plt.savefig('test_accuracy_comparison.png', dpi=300)
    plt.close()

    # Plot 2: Global EER (lower is better)
    plt.figure(figsize=(12, 8))
    bars = sns.barplot(x='Model', y='Global EER (%)', hue='Model Type', data=df, palette='viridis')
    plt.title('Global Equal Error Rate (EER) by Model (Lower is Better)', fontsize=16)
    plt.xticks(rotation=45, ha='right')
    plt.ylim(0, max(df['Global EER (%)']) * 1.1)  # Start from 0
    # Fix annotation to avoid the black 0.00% text
    for i, bar in enumerate(bars.patches):
        if bar.get_height() > 0:  # Only annotate if there's actually a value
            bars.annotate(f"{bar.get_height():.2f}%",
                         (bar.get_x() + bar.get_width()/2, bar.get_height()),
                         ha='center', va='bottom', fontsize=10)
    plt.tight_layout()
    plt.savefig('global_eer_comparison.png', dpi=300)
    plt.close()

    # Plot 3: Average Per-User EER (lower is better)
    plt.figure(figsize=(12, 8))
    bars = sns.barplot(x='Model', y='Avg Per-User EER (%)', hue='Model Type', data=df, palette='viridis')
    plt.title('Average Per-User EER by Model (Lower is Better)', fontsize=16)
    plt.xticks(rotation=45, ha='right')
    plt.ylim(0, max(df['Avg Per-User EER (%)']) * 1.1)  # Start from 0
    for i, bar in enumerate(bars.patches):
        if bar.get_height() > 0:  # Only annotate if there's actually a value
            bars.annotate(f"{bar.get_height():.2f}%",
                         (bar.get_x() + bar.get_width()/2, bar.get_height()),
                         ha='center', va='bottom', fontsize=10)
    plt.tight_layout()
    plt.savefig('avg_per_user_eer_comparison.png', dpi=300)
    plt.close()

    # Plot 4: Simple accuracy vs EER scatter plot
    plt.figure(figsize=(10, 8))
    plt.scatter(df['Global EER (%)'], df['Test Accuracy (%)'],
               s=120, c=[sns.color_palette('viridis', 3)[i] for i in pd.Categorical(df['Model Type']).codes],
               alpha=0.8, edgecolors='w')

    # Add labels to each point
    for i, model in enumerate(df['Model']):
        plt.annotate(model,
                    (df['Global EER (%)'].iloc[i], df['Test Accuracy (%)'].iloc[i]),
                    xytext=(7, 0), textcoords='offset points', fontsize=10)

    plt.title('Comparison: Test Accuracy vs Global EER', fontsize=16)
    plt.xlabel('Global EER (%)', fontsize=14)
    plt.ylabel('Test Accuracy (%)', fontsize=14)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()

    # Create custom legend for model types
    from matplotlib.lines import Line2D
    legend_elements = [
        Line2D([0], [0], marker='o', color='w', markerfacecolor=sns.color_palette('viridis', 3)[i],
               markersize=10, label=t) for i, t in enumerate(df['Model Type'].unique())
    ]
    plt.legend(handles=legend_elements, title='Architecture')

    plt.savefig('accuracy_vs_eer_comparison.png', dpi=300)
    plt.close()

    # Print a summary table
    print("Model Performance Summary (Ranked by Test Accuracy)")
    summary = df[['Model', 'Test Accuracy (%)', 'Global EER', 'Avg Per-User EER']].copy()
    summary['Global EER'] = summary['Global EER'].apply(lambda x: f"{x:.4f} ({x*100:.2f}%)")
    summary['Avg Per-User EER'] = summary['Avg Per-User EER'].apply(lambda x: f"{x:.4f} ({x*100:.2f}%)")
    summary['Test Accuracy (%)'] = summary['Test Accuracy (%)'].apply(lambda x: f"{x:.2f}%")
    print(summary.to_string(index=False))

def flow_diagram():
    import graphviz

    # Create a directed graph
    dot = graphviz.Digraph('project_workflow',
                           format='png', engine='dot')

    # Graph styling with larger size
    dot.attr('graph',
             rankdir='LR',          # Left to right layout
             splines='ortho',       # Orthogonal lines
             nodesep='1.2',         # Increased node separation
             ranksep='0.8',         # Increased rank separation
             fontname='Arial',
             fontsize='36')         # Significantly larger font

    dot.attr('node',
             shape='box',
             style='filled,rounded',
             fillcolor='#39599a',   # Blue
             fontname='Arial',
             fontcolor='white',
             fontsize='32',         # Much larger font
             width='3.5',           # Wider boxes
             height='2.2',          # Taller boxes
             margin='0.4,0.3')      # More margin for text

    dot.attr('edge',
             color='#7f8c8d',       # Gray
             penwidth='3',          # Thicker lines
             arrowsize='1.2')       # Larger arrows

    # Define the nodes for each step with detailed labels
    dot.node('collection',
             label='Data Collection')

    dot.node('preprocessing',
             label='Data Preprocessing')

    dot.node('preparation',
             label='Model Preparation')

    dot.node('training',
             label='Model Training & Test')

    dot.node('conversion',
             label='Conversion to Mobile')

    dot.node('comparison',
             label='Performance Comparison')

    # Define the edges
    dot.edge('collection', 'preprocessing')
    dot.edge('preprocessing', 'preparation')
    dot.edge('preparation', 'training')
    dot.edge('training', 'conversion')
    dot.edge('conversion', 'comparison')

    # Set a larger DPI for higher resolution
    dot.attr(dpi='300')

    # Render the graph
    dot.render('project_workflow', view=True, cleanup=True)

    print("Workflow diagram created as 'project_workflow.png'")

flow_diagram()

def plot_bvp():
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator

    # Load the BVP data
    file_path = 'BVP.csv'
    data = pd.read_csv(file_path, header=None)

    # Flatten the row and extract all values
    all_values = data.values.flatten()

    # The first value is timestamp, the second is sampling rate
    timestamp = all_values[0]
    sampling_rate = int(all_values[1])
    bvp_data = all_values[2:]  # BVP signal starts here

    print("Total BVP points:", len(bvp_data))

    # Determine 5-second window
    window_size = 5  # seconds
    points_per_window = sampling_rate * window_size

    if len(bvp_data) < points_per_window:
        print(f"Not enough data for a 5-second window. Found {len(bvp_data)} points.")
        segment = bvp_data
        actual_window_size = len(segment) / sampling_rate
    else:
        mid_idx = len(bvp_data) // 2
        start_idx = max(0, mid_idx - points_per_window // 2)
        end_idx = start_idx + points_per_window
        segment = bvp_data[start_idx:end_idx]
        actual_window_size = window_size

    # Create time axis
    time = np.linspace(0, actual_window_size, len(segment))

    # Plot
    fig, ax = plt.subplots(figsize=(12, 6), facecolor='#f8f8f8')
    ax.set_facecolor('#f8f8f8')

    ax.plot(time, segment, color='#D20000', linewidth=1.8)
    ax.fill_between(time, segment, np.min(segment), alpha=0.15, color='#FF0000')

    ax.grid(True, which='major', linestyle='-', linewidth=0.5, color='#DDDDDD')
    ax.minorticks_on()
    ax.grid(which='minor', linestyle=':', linewidth=0.5, color='#EEEEEE')
    ax.set_axisbelow(True)

    ax.xaxis.set_major_locator(MultipleLocator(1.0))
    ax.xaxis.set_minor_locator(MultipleLocator(0.2))

    fig.suptitle("Blood Volume Pulse (BVP) Signal", fontsize=16, fontweight='bold', color='#333333')
    ax.set_title("ECSMP dataset sample", fontsize=12, style='italic', color='#555555', pad=10)
    ax.set_xlabel("Time (seconds)", fontsize=12, labelpad=10, color='#333333')
    ax.set_ylabel("Amplitude", fontsize=12, labelpad=10, color='#333333')

    plt.figtext(0.02, 0.02, f"User ID: 1 | {actual_window_size:.1f}-second window | Sampling rate: {sampling_rate} Hz",
                fontsize=10, color='#555555', ha='left')

    info = "Blood Volume Pulse reflects cardiovascular activity\nand can be used for biometric identification"
    plt.figtext(0.98, 0.02, info, fontsize=9, color='#555555', ha='right',
                bbox=dict(boxstyle='round,pad=0.5', facecolor='#f0f0f0', alpha=0.7))

    plt.tight_layout()
    plt.subplots_adjust(bottom=0.15)
    plt.savefig('bvp_visualization.png', dpi=300, bbox_inches='tight')
    plt.show()


#plot_bvp()

def plot_eda():
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator

    # Load the EDA data
    file_path = 'EDA.csv'
    data = pd.read_csv(file_path, header=None)

    # Flatten and extract values
    all_values = data.values.flatten()
    timestamp = all_values[0]
    sampling_rate = int(all_values[1])
    eda_data = all_values[2:]

    print("Total EDA points:", len(eda_data))

    # Determine 5-second window
    window_size = 5  # seconds
    points_per_window = sampling_rate * window_size

    if len(eda_data) < points_per_window:
        print(f"Not enough data for a 5-second window. Found {len(eda_data)} points.")
        segment = eda_data
        actual_window_size = len(segment) / sampling_rate
    else:
        mid_idx = len(eda_data) // 2
        start_idx = max(0, mid_idx - points_per_window // 2)
        end_idx = start_idx + points_per_window
        segment = eda_data[start_idx:end_idx]
        actual_window_size = window_size

    # Create time axis
    time = np.linspace(0, actual_window_size, len(segment))

    # Plot
    fig, ax = plt.subplots(figsize=(12, 6), facecolor='#f8f8f8')
    ax.set_facecolor('#f8f8f8')

    ax.plot(time, segment, color='#008080', linewidth=1.8)
    ax.fill_between(time, segment, np.min(segment), alpha=0.15, color='#00CCCC')

    ax.grid(True, which='major', linestyle='-', linewidth=0.5, color='#DDDDDD')
    ax.minorticks_on()
    ax.grid(which='minor', linestyle=':', linewidth=0.5, color='#EEEEEE')
    ax.set_axisbelow(True)

    ax.xaxis.set_major_locator(MultipleLocator(1.0))
    ax.xaxis.set_minor_locator(MultipleLocator(0.2))

    fig.suptitle("Electrodermal Activity (EDA) Signal", fontsize=16, fontweight='bold', color='#333333')
    ax.set_title("ECSMP dataset sample", fontsize=12, style='italic', color='#555555', pad=10)
    ax.set_xlabel("Time (seconds)", fontsize=12, labelpad=10, color='#333333')
    ax.set_ylabel("Amplitude (µS)", fontsize=12, labelpad=10, color='#333333')

    plt.figtext(0.02, 0.02, f"User ID: 1 | {actual_window_size:.1f}-second window | Sampling rate: {sampling_rate} Hz",
                fontsize=10, color='#555555', ha='left')

    info = "EDA reflects changes in skin conductance\nlinked to psychological or physiological arousal"
    plt.figtext(0.98, 0.02, info, fontsize=9, color='#555555', ha='right',
                bbox=dict(boxstyle='round,pad=0.5', facecolor='#f0f0f0', alpha=0.7))

    plt.tight_layout()
    plt.subplots_adjust(bottom=0.15)
    plt.savefig('eda_visualization.png', dpi=300, bbox_inches='tight')
    plt.show()

#plot_eda()

def plot_both_signals():
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator

    # Create figure with two subplots, one above the other
    fig, (ax_bvp, ax_eda) = plt.subplots(2, 1, figsize=(18, 10), facecolor='#f8f8f8')

    # ------ BVP PLOT (TOP) ------
    # Load the BVP data
    file_path = 'BVP.csv'
    with open(file_path, 'r') as f:
        lines = f.readlines()

    # Parse data
    all_values = []
    for line in lines:
        all_values.extend([float(x) for x in line.strip().split()])

    # Extract metadata and signal
    timestamp = all_values[0]
    sampling_rate_bvp = int(all_values[1])
    bvp_data = all_values[2:]

    print("Total BVP points:", len(bvp_data))

    # Define 5-second window
    window_size = 5  # seconds
    points_per_window_bvp = sampling_rate_bvp * window_size

    if len(bvp_data) < points_per_window_bvp:
        print(f"Not enough BVP data for a 5-second window. Found {len(bvp_data)} points.")
        segment_bvp = bvp_data
        actual_window_size_bvp = len(segment_bvp) / sampling_rate_bvp
    else:
        mid_idx = len(bvp_data) // 2
        start_idx = max(0, mid_idx - points_per_window_bvp // 2)
        end_idx = start_idx + points_per_window_bvp
        segment_bvp = bvp_data[start_idx:end_idx]
        actual_window_size_bvp = window_size

    # Create time axis
    time_bvp = np.linspace(0, actual_window_size_bvp, len(segment_bvp))

    # Plot BVP
    ax_bvp.set_facecolor('#f8f8f8')
    ax_bvp.plot(time_bvp, segment_bvp, color='#D20000', linewidth=1.8)

    if len(segment_bvp) > 0:
        min_val_bvp = np.min(segment_bvp)
        ax_bvp.fill_between(time_bvp, segment_bvp, min_val_bvp, alpha=0.15, color='#FF0000')

    ax_bvp.grid(True, which='major', linestyle='-', linewidth=0.5, color='#DDDDDD')
    ax_bvp.minorticks_on()
    ax_bvp.grid(which='minor', linestyle=':', linewidth=0.5, color='#EEEEEE')
    ax_bvp.set_axisbelow(True)

    ax_bvp.xaxis.set_major_locator(MultipleLocator(1.0))
    ax_bvp.xaxis.set_minor_locator(MultipleLocator(0.2))

    ax_bvp.set_title("Blood Volume Pulse (BVP) Signal", fontsize=14, fontweight='bold', color='#333333')
    ax_bvp.set_ylabel("Amplitude", fontsize=12, labelpad=10, color='#333333')

    # Add user info to BVP plot
    ax_bvp.text(0.02, 0.05, f"User ID: 1 | Sampling rate: {sampling_rate_bvp} Hz",
                fontsize=9, transform=ax_bvp.transAxes, color='#555555', ha='left')

    # ------ EDA PLOT (BOTTOM) ------
    # Load the EDA data
    file_path = 'EDA.csv'
    try:
        with open(file_path, 'r') as f:
            lines = f.readlines()

        # Parse data
        all_values = []
        for line in lines:
            all_values.extend([float(x) for x in line.strip().split()])

        # Extract metadata and signal
        timestamp = all_values[0]
        sampling_rate_eda = int(all_values[1])
        eda_data = all_values[2:]

        print("Total EDA points:", len(eda_data))

        # Define 5-second window
        points_per_window_eda = sampling_rate_eda * window_size

        if len(eda_data) < points_per_window_eda:
            print(f"Not enough EDA data for a 5-second window. Found {len(eda_data)} points.")
            segment_eda = eda_data
            actual_window_size_eda = len(segment_eda) / sampling_rate_eda
        else:
            mid_idx = len(eda_data) // 2
            start_idx = max(0, mid_idx - points_per_window_eda // 2)
            end_idx = start_idx + points_per_window_eda
            segment_eda = eda_data[start_idx:end_idx]
            actual_window_size_eda = window_size

        # Create time axis
        time_eda = np.linspace(0, actual_window_size_eda, len(segment_eda))

        # Plot EDA
        ax_eda.set_facecolor('#f8f8f8')
        ax_eda.plot(time_eda, segment_eda, color='#008080', linewidth=1.8)

        if len(segment_eda) > 0:
            min_val_eda = np.min(segment_eda)
            ax_eda.fill_between(time_eda, segment_eda, min_val_eda, alpha=0.15, color='#00CCCC')

        ax_eda.grid(True, which='major', linestyle='-', linewidth=0.5, color='#DDDDDD')
        ax_eda.minorticks_on()
        ax_eda.grid(which='minor', linestyle=':', linewidth=0.5, color='#EEEEEE')
        ax_eda.set_axisbelow(True)

        ax_eda.xaxis.set_major_locator(MultipleLocator(1.0))
        ax_eda.xaxis.set_minor_locator(MultipleLocator(0.2))

        ax_eda.set_title("Electrodermal Activity (EDA) Signal", fontsize=14, fontweight='bold', color='#333333')
        ax_eda.set_xlabel("Time (seconds)", fontsize=12, labelpad=10, color='#333333')
        ax_eda.set_ylabel("Amplitude (µS)", fontsize=12, labelpad=10, color='#333333')

        # Add user info to EDA plot
        ax_eda.text(0.02, 0.05, f"User ID: 1 | Sampling rate: {sampling_rate_eda} Hz",
                    fontsize=9, transform=ax_eda.transAxes, color='#555555', ha='left')
    except FileNotFoundError:
        ax_eda.text(0.5, 0.5, "EDA.csv file not found",
                    ha='center', va='center', fontsize=14, color='#888888')

    # Add overall title and description
    fig.suptitle("Physiological Signals from ECSMP Dataset",
                 fontsize=16, fontweight='bold', color='#333333', y=0.98)

    # Add descriptive text at bottom
    info = "These biometric signals can be used for user identification\nand physiological state monitoring"
    plt.figtext(0.98, 0.01, info, fontsize=9, color='#555555', ha='right',
                bbox=dict(boxstyle='round,pad=0.5', facecolor='#f0f0f0', alpha=0.7))

    plt.tight_layout()
    plt.subplots_adjust(top=0.92, hspace=0.3, bottom=0.08)
    plt.savefig('bvp_eda_visualization.png', dpi=300, bbox_inches='tight')
    plt.show()


#plot_both_signals()

def plot_global_eer():
    # Load the data from CSV file
    df = pd.read_csv('../logs/model_performance_log.csv')

    # Take only the first 10 models (excluding header)
    df = df.head(10)

    # Sort models by Global EER for better visualization (lower is better)
    df = df.sort_values('Global EER', ascending=True)

    # Convert EER values to percentage
    df['Global EER (%)'] = df['Global EER'] * 100

    # Create a new column to identify the selected model
    df['Selected'] = df['Model'].apply(lambda x: x == 'LSTM_Transformer')

    # Set global styling and use a font that supports symbols
    sns.set_style("whitegrid")
    plt.rcParams['font.family'] = 'DejaVu Sans'  # Font with better Unicode support
    plt.figure(figsize=(24, 10))

    # Create a custom palette of blue shades
    blue_palette = sns.color_palette("Blues_d", len(df))

    # Create the bar plot with blue shades
    bars = sns.barplot(
        x='Model',
        y='Global EER (%)',
        data=df,
        palette=blue_palette
    )

    # Increase font size for title and labels
    plt.title('Global Equal Error Rate (EER) by Model (Lower is Better)', fontsize=26)
    plt.xlabel('Model', fontsize=22)
    plt.ylabel('Global EER (%)', fontsize=22)

    # Make tick labels larger
    plt.xticks(rotation=45, ha='right', fontsize=18)
    plt.yticks(fontsize=18)

    plt.ylim(0, max(df['Global EER (%)']) * 1.1)

    # Add value annotations to the bars
    for i, bar in enumerate(bars.patches):
        if bar.get_height() > 0:
            # Determine if this is the selected model
            is_selected = df['Selected'].iloc[i]

            # Make selected model's annotation bold with red color
            fontweight = 'bold' if is_selected else 'normal'
            color = '#D20000' if is_selected else 'black'

            bars.annotate(f"{bar.get_height():.2f}%",
                          (bar.get_x() + bar.get_width() / 2, bar.get_height()),
                          ha='center', va='bottom', fontsize=20,
                          fontweight=fontweight, color=color)

            # Add a marker above the selected model - using * instead of ★
            if is_selected:
                bar_height = bar.get_height()
                bar_x = bar.get_x() + bar.get_width() / 2
                plt.text(bar_x, bar_height + (max(df['Global EER (%)']) * 0.02),
                         "*", color='#D20000', fontsize=40, ha='center', va='bottom',
                         fontweight='bold')

                # Add a subtle red border to the selected model's bar
                bar.set_edgecolor('#D20000')
                bar.set_linewidth(2.5)

    # Add legend for the selected model
    from matplotlib.patches import Patch
    legend_elements = [
        Patch(facecolor='none', edgecolor='#D20000', linewidth=2.5,
              label='Selected model (LSTM_Transformer)')
    ]
    plt.legend(handles=legend_elements, loc='upper right', fontsize=18)

    plt.tight_layout()
    plt.savefig('global_eer_comparison_highlighted.png', dpi=300)
    plt.show()

#plot_global_eer()

def plot_model_comparison():
    # Parse the data, excluding the bigger model variants
    datasets = ["EMOGNITION", "ECSMP", "UBFC"]

    accuracy_data = {
        "Full": [98.94, 98.89, 91.95],
        "TFLite": [98.95, 98.86, 91.88]
    }

    eer_data = {
        "Full": [0.23, 0.19, 1.63],
        "TFLite": [0.24, 0.20, 1.63]
    }

    inference_data = {
        "Full": [13.23, 14.87, 5.67],
        "TFLite": [49.82, 81.98, 14.00]
    }

    model_size_data = {
        "Full": [723.51, 715.47, 698.12],
        "TFLite": [101.28, 102.13, 101.45]
    }

    # Set up the figure
    fig, axes = plt.subplots(2, 2, figsize=(24, 12))

    # Set style
    sns.set_style("whitegrid")

    # Two shades of blue palette
    palette = ["#1f77b4", "#9ecae1"]  # Dark blue and light blue

    # Function to create grouped bar plots
    def create_grouped_bar(ax, data_dict, title, ylabel, ylim=None, format_str="{:.1f}"):
        # Create DataFrame
        df = pd.DataFrame(data_dict)
        df['Dataset'] = datasets

        # Melt the DataFrame for easier plotting
        df_melted = df.melt(id_vars=['Dataset'], var_name='Model Type', value_name='Value')

        # Create the grouped bar plot
        bars = sns.barplot(x='Dataset', y='Value', hue='Model Type',
                           data=df_melted, palette=palette, ax=ax)

        # Properly set x-ticks before setting labels
        ax.set_xticks(range(len(datasets)))
        ax.set_xticklabels(datasets, rotation=45, ha='right', fontsize=16)

        # Add value labels on top of bars
        for container in bars.containers:
            bars.bar_label(container, fmt=format_str, fontsize=14)

        # Set title and labels
        ax.set_title(title, fontsize=22, fontweight='bold', pad=15)
        ax.set_ylabel(ylabel, fontsize=20)
        ax.set_xlabel('', fontsize=20)

        # Set y-axis limits if specified
        if ylim:
            ax.set_ylim(ylim)

        ax.tick_params(axis='y', labelsize=16)

        # Add legend
        ax.legend(fontsize=18, title_fontsize=18)

    # 1. Accuracy Plot
    create_grouped_bar(axes[0, 0], accuracy_data, 'Model Accuracy Comparison',
                       'Accuracy (%)', ylim=(90, 100), format_str="{:.2f}%")

    # 2. Global EER Plot
    create_grouped_bar(axes[0, 1], eer_data, 'Global EER Comparison (Lower is Better)',
                       'Equal Error Rate (%)', ylim=(0, 2.0), format_str="{:.2f}%")

    # 3. Inference Time Plot
    create_grouped_bar(axes[1, 0], inference_data, 'Inference Time Comparison (Lower is Better)',
                       'Inference Time (seconds)', format_str="{:.1f}s")

    # 4. Model Size Plot
    create_grouped_bar(axes[1, 1], model_size_data, 'Model Size Comparison',
                       'Size (KB)', format_str="{:.1f}KB")

    # Add overall title
    fig.suptitle('Model Performance Metrics: Full Model vs TFLite', fontsize=26, fontweight='bold', y=0.98)

    # Adjust layout
    plt.tight_layout()
    plt.subplots_adjust(top=0.92)

    # Save and show the figure
    plt.savefig('model_comparison_metrics.png', dpi=300, bbox_inches='tight')
    plt.show()


# Call the function
#plot_model_comparison()